﻿using Developer.Core.FrameWork.EventBus.Option;
using Developer.Core.FrameWork.EventBus.SubscriptionManager.RabbitMQEventBus;
using Developer.Core.FrameWork.GlobalVar;
using Developer.Core.FrameWork.HelpFile;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System;

namespace Developer.Core.FrameWork.EventBus.Extensions
{
    /// <summary>
    /// RabbitMQ事件总线扩展类
    /// </summary>
    public static class RabbitMQExtensions
    {
        public static void AddRabbitMQService(this IServiceCollection service)
        {
            if (service == null)
                throw new ArgumentNullException(nameof(service));

            RabbitMqOption option = Appsettings.app<RabbitMqOption>("RabbitMQ");

            // 是否开启RabbitMQ消息队列
            if (GlobalVars.RabbitMQ)
            {
                service.AddSingleton<IRabbitMQConnection>(sp =>
                {
                    var logger = sp.GetRequiredService<ILogger<RabbitMQConnection>>();

                    var factory = new ConnectionFactory()
                    {
                        HostName = option.Connection,
                        DispatchConsumersAsync = true
                    };

                    if (!string.IsNullOrWhiteSpace(option.UserName))
                        factory.UserName = option.UserName;

                    if (!string.IsNullOrWhiteSpace(option.Password))
                        factory.Password = option.Password;

                    int retryCount = 5;

                    if (option.RetryCount > 0)
                        retryCount = option.RetryCount;

                    return new RabbitMQConnection(factory, logger, retryCount);
                });
            }
        }
    }
}
